<?php 
namespace Admin\Model;
use Think\Model;
/**
 * create table art_iptouser(
    uid INT(8) NOT NULL,
    ip INT(8) NOT NULL,
    uptime INT(20) NOT NULL,
    FOREIGN KEY(uid) REFERENCES art_user(id) ON UPDATE CASCADE ON DELETE RESTRICT,
    FOREIGN KEY(ip) REFERENCES art_ip(id) ON UPDATE CASCADE ON DELETE RESTRICT,
    PRIMARY KEY(uid, ip));

*/
class IptouserModel extends Model{
	private $_uid;
    private $_ip;
    private $_uptime;
    public function getUsers(){ // 获取全部信息,通过用户索引
        $temp = $this->select();
        $res = array();
        foreach($temp as $v){
            $res[$v['uid']][] = $v;
        }
        return $res;
    }
    
    public function getByUser(){
        return $this->where(array('uid'=>$this->_uid))->select();
    }
    
    public function allot($uid, $ips){  // 为用户分配ip地址，$ips是一个数组参数
        $this->_uid = $uid;
        $now = $this->getByUser();
        foreach($ips as $ip){   // 遍历所有输入项，检查是否有新增的，如果有则新增数据
            $this->_ip = $ip;
            $this->addOne();
        }
        foreach($now as $ip){   // 遍历所有已经存在的项，检查是否有不存在于用户输入的，如果有则删除
            if(!in_array($ip['ip'], $ips)){
                $this->_ip = $ip['ip'];
                $this->deleteOne();
            }
        }
        $this->freshCache();
        return true;
    }
    
    public function addOne(){
        if(!$this->isHas()){
            $data['uid'] = $this->_uid;
            $data['ip'] = $this->_ip;
            $data['uptime'] = time();
            return $this->add($data);
        }
        return false;
    }
    
    public function deleteOne(){
        if($this->isHas()){
            $data['uid'] = $this->_uid;
            $data['ip'] = $this->_ip;
            return $this->where($data)->delete();
        }
        return false;
    }
    
    private function isHas(){
        if($this->where(array('uid'=>$this->_uid, 'ip'=>$this->_ip))->find() == null){
            return false;
        }
        return true;
    }
    
    private function freshCache(){
        $iptousers = $this->select();
        S('iptousers', $iptousers);
    }
}